import Pc
import PcData
import networkx as nx
import matplotlib.pyplot as plt

if __name__ == "__main__":
    dependency_pc = Pc.DependencyAnalysis()
    data_pc = PcData.DataOperator()



    data = data_pc.getData()
    print(data)

    row_count = sum(1 for row in data)
    p = dependency_pc.pc(
        suffStat={"C": data.corr().values, "n": data.values.shape[0]},
        alpha=0.05,
        labels=[str(i) for i in range(row_count)],
        indepTest = dependency_pc.gauss_ci_test,
        verbose= True
    )
    print(p['g_w'])
    print(p['g'])

    labels = [str(i) for i in range(row_count)]
    G = nx.DiGraph()  # 创建空有向图
    # 创建空有向图
    graph = p['g']
    for i in range(len(graph)):
        G.add_node(labels[i])
        for j in range(len(graph[i])):
            if graph[i][j] > 0:
                graph[i][j] = round(graph[i][j], 2)
                G.add_edges_from([(labels[i], labels[j], {'weight': round(graph[i][j], 2)})])

    pos = nx.circular_layout(G)
    edge_labels = nx.get_edge_attributes(G, 'weight')
    nx.draw(G, pos, with_labels=True)
    nx.draw_networkx_edge_labels(G, pos,edge_labels=edge_labels)
    plt.show()
    # 存入数据库
    bytes_graph = graph.tobytes()
    # bytes_graph = b'\x01\x02\x03\x04\x05'
    print(bytes_graph)

    data_pc.insert(bytes_graph)